package com.huike.clues.service.impl;

import com.huike.clues.service.ISysFileService;
import com.huike.common.config.MinioConfig;
import com.huike.common.core.domain.AjaxResult;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
@Slf4j
public class SysFileServiceImpl implements ISysFileService {

    @Autowired
    private MinioConfig minioConfig;

    /**
     * 文件上传至Minio
     */
    @Override
    public AjaxResult upload(MultipartFile file) throws Exception {
        try {
        //创建Minio的连接对象
        MinioClient minioClient = MinioClient.builder()
                .endpoint(minioConfig.getEndpoint() + ":" + minioConfig.getPort())
                .credentials(minioConfig.getAccessKey(), minioConfig.getSecretKey())
                .build();

        String bucket = "huike-crm";
        //判断文件存储的桶是否存在
        // 如果不存在, 则创建"huike-crm"桶
        boolean found =
                minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucket).build());
        if (!found){
            //创建新的桶"huike-crm"
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucket).build());
        }else {
            System.out.println("桶'huike-crm'已存在!");
        }
        //操作文件，文件上传
        //上传 file 作为对象名
        //获取原始文件名
        String originalFilename = file.getOriginalFilename();
        //获取文件后缀
        assert originalFilename != null;
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //使用UUID重新洗生成文件名,防止文件名重复
        String fileName = UUID.randomUUID().toString()+suffix;

        //获取文件InputStream流
        InputStream inputStream = file.getInputStream();

        //将文件转存到目录
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(bucket)
                .object(fileName)
                .stream(inputStream,inputStream.available(),-1)
                .contentType(file.getContentType())
                .build());
        //封装访问的url给前端
        fileName = "/" + bucket + "/"+fileName;
        String url = "http://192.168.1.8:9000"+ fileName;
        AjaxResult result = AjaxResult.success("成功上传");
        result.put("fileName", fileName);
        result.put("url",url);

        return result;

       /* // Upload '/home/user/Photos/asiaphotos.zip' as object name
        minioClient.uploadObject(
                UploadObjectArgs.builder()
                        .bucket("huike-crm")
                        .object(fileName)
                        .filename(file)
                        .build());*/

        } catch (IOException e) {
            throw new RuntimeException(e);

        }
    }

}
